package com.itms.tool;

import android.app.Activity;
import android.os.Bundle;

import com.actionbarsherlock.app.SherlockFragment;
import com.itms.tool.data.DatabaseHelper;
import com.itms.tool.data.Object;

public abstract class ObjectFragment extends SherlockFragment {

	private NewObjectActivity mNewObjectActivity;
	private Object mObject;
	private DatabaseHelper mHelper;
	
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		if (!(activity instanceof NewObjectActivity)) {
			throw new IllegalStateException("Fragment: " + getClass() + " is not attached to NewObjectActivity");
		}
		mNewObjectActivity = (NewObjectActivity) activity;
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		mObject = mNewObjectActivity.getObject();
		mHelper = mNewObjectActivity.getHelper();
		initContentView(mObject, savedInstanceState);
	}
	
	public NewObjectActivity getNewObjectActivity() {
		if (mNewObjectActivity == null) {
			throw new IllegalStateException("fragment: " + getClass() + " has not been attached to activity");
		}
		return mNewObjectActivity;
	}
	
	public Object getObject() {
		return mObject;
	}
	
	public DatabaseHelper getHelper() {
		return mHelper;
	}
	
	public void toast(String message) {
		mNewObjectActivity.toast(message);
	}
	
	public void toast(int message) {
		mNewObjectActivity.toast(message);
	}
	
	protected abstract void initContentView(Object object, Bundle savedInstanceState);
	
	/** Set properties of <code>object</code> from view
	 *  associated to this fragment.<br />
	 *  <b>NOTE:</b> do not save object itself to database here, 
	 *  it will be saved in {@link NewObjectActivity#onPause()}**/
	protected abstract void saveObject(Object object);
	
	@Override
	public void onPause() {
		super.onPause();
		saveObject(mObject);
	}
	
	@Override
	public void onDetach() {
		super.onDetach();
		mNewObjectActivity = null;
	}
}
